﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Animation;

namespace ZeroBug.EasyFlow.Resources
{
    public static partial class Cattach
    {
        public static CornerRadius GetButtonCornerRadius(DependencyObject obj)
        {
            return (CornerRadius)obj.GetValue(ButtonCornerRadiusProperty);
        }
        public static void SetButtonCornerRadius(DependencyObject obj, CornerRadius value)
        {
            obj.SetValue(ButtonCornerRadiusProperty, value);
        }
        public static readonly DependencyProperty ButtonCornerRadiusProperty =
            DependencyProperty.RegisterAttached("ButtonCornerRadius", typeof(CornerRadius), typeof(Cattach), new PropertyMetadata(default(CornerRadius)));

        public static string GetExpanderIcon(DependencyObject obj)
        {
            return (string)obj.GetValue(ExpanderIconProperty);
        }
        public static void SetExpanderIcon(DependencyObject obj, string value)
        {
            obj.SetValue(ExpanderIconProperty, value);
        }
        public static readonly DependencyProperty ExpanderIconProperty =
            DependencyProperty.RegisterAttached("ExpanderIcon", typeof(string), typeof(Cattach), new PropertyMetadata(""));

        public static Brush GetBackground(DependencyObject obj)
        {
            return (Brush)obj.GetValue(BackgroundProperty);
        }
        public static void SetBackground(DependencyObject obj, Brush value)
        {
            obj.SetValue(BackgroundProperty, value);
        }
        public static readonly DependencyProperty BackgroundProperty =
            DependencyProperty.RegisterAttached("Background", typeof(Brush), typeof(Cattach), new PropertyMetadata(null, backgroundChangedCallback));

        private static void backgroundChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if(d is FrameworkElement element && e.NewValue is SolidColorBrush colorBrush)
            {
                AnimateBrushProperty(element, colorBrush, "Background");
            }
        }

        private static void AnimateBrushProperty(FrameworkElement element, SolidColorBrush colorBrush, string propertyName)
        {
            var property = element.GetType().GetProperty(propertyName);
            if (property == null) return;
            var currentBrush = property.GetValue(element) as SolidColorBrush;
            if(currentBrush == null || currentBrush.IsFrozen)
            {
                currentBrush = new SolidColorBrush(colorBrush.Color);
                property.SetValue(element, currentBrush);
            }
            currentBrush.BeginAnimation(SolidColorBrush.ColorProperty, new ColorAnimation()
            {
                To = colorBrush.Color,
                Duration = TimeSpan.FromSeconds(0.3),
            });
        }
    }
}
